package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dataTransmit.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.pageQuery.HistoryOrdersPageQuery;
import com.sky.result.PageResult;
import com.sky.service.OrderDetailService;
import com.sky.service.OrdersService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.view.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    //客户下单
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //如果地址为空
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.selectById(addressBookId);
        if(addressBookId==null||addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断是否超出配送范围
        checkOutOfRange(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //查询购物车表的数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(queryWrapper);
        //如果购物车为空
        if(shoppingCarts==null||shoppingCarts.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入数据
        Orders orders = BeanUtil.copyProperties(ordersSubmitDTO, Orders.class);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        save(orders);
        //向订单详细批量插入数据
        List<OrderDetail> orderDetails = BeanUtil.copyToList(shoppingCarts, OrderDetail.class);
        orderDetails.forEach(o->{
            o.setOrderId(orders.getId());
            o.setId(null);
        });
        orderDetailService.saveBatch(orderDetails);
        //删除购物车表里的数据
        shoppingCartMapper.delete(queryWrapper);
        //返回数据
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
    }

    //客户支付订单
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        //当前登录客户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal("0.01"), //支付金额，单位 元
                "牛马外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
        OrderPaymentVO orderPaymentVO = jsonObject.toJavaObject(OrderPaymentVO.class);
        orderPaymentVO.setPackageStr(jsonObject.getString("package"));
        return orderPaymentVO;
    }

    //客户支付订单成功
    public void paySuccess(String outTradeNo) {
        //根据订单号查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getNumber, outTradeNo);
        Orders ordersDB = getOne(queryWrapper);
        //根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        updateById(orders);
        //向商家推送消息
        NotifyVO notifyVO = new NotifyVO(1, orders.getId(), outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(notifyVO));
    }

    //客户查询历史订单
    @Override
    public PageResult historyOrders(HistoryOrdersPageQuery historyOrdersPageQuery) {
        Page<Orders> page = Page.of(historyOrdersPageQuery.getPage(), historyOrdersPageQuery.getPageSize());
        Page<Orders> result = lambdaQuery()
                .eq(Orders::getUserId, BaseContext.getCurrentId())
                .eq(historyOrdersPageQuery.getStatus()!=null,Orders::getStatus,historyOrdersPageQuery.getStatus())
                .page(page);
        List<OrderVO> orderVOS = BeanUtil.copyToList(result.getRecords(), OrderVO.class);
        for (OrderVO orderVO : orderVOS) {
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                    .eq(OrderDetail::getOrderId, orderVO.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
            orderVO.setOrderDetailList(orderDetails);
        }
        return new PageResult(result.getTotal(),orderVOS);
    }

    //客户再来一单
    @Transactional
    @Override
    public void repetition(Long id) {
        //判断订单是否存在
        checkOrdersExist(id);
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
        List<ShoppingCart> shoppingCarts = BeanUtil.copyToList(orderDetails, ShoppingCart.class);
        Long userId = BaseContext.getCurrentId();
        shoppingCarts.forEach(s->s.setUserId(userId));
        shoppingCartService.saveBatch(shoppingCarts);
    }

    //客户查询订单详细信息
    @Override
    public OrderVO orderDetail(Long id) {
        //判断订单是否存在
        checkOrdersExist(id);
        Orders orders = getById(id);
        OrderVO orderVO = BeanUtil.copyProperties(orders, OrderVO.class);
        LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper1);
        String addressBookString = getAddressBookString(orders.getAddressBookId());
        orderVO.setAddress(addressBookString);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    //商家取消订单
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //判断订单是否存在
        Orders orders = checkOrdersExist(ordersCancelDTO.getId());
        //如果客户已支付需退款
        if(orders.getPayStatus().equals(Orders.PAID)) refund(orders.getNumber(),orders.getAmount());
        //更新订单信息
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                .eq(Orders::getId, ordersCancelDTO.getId())
                .set(Orders::getCancelReason, ordersCancelDTO.getCancelReason())
                .set(Orders::getStatus, Orders.CANCELLED)
                .set(Orders::getCancelTime, LocalDateTime.now());
        update(updateWrapper);
    }

    //商家查询订单统计数据
    @Override
    public OrderStatisticsVO statistics() {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //待派送
        queryWrapper.eq(Orders::getStatus,Orders.CONFIRMED);
        Integer confirmed = (int) count(queryWrapper);
        queryWrapper.clear();
        //派送中
        queryWrapper.eq(Orders::getStatus,Orders.DELIVERY_IN_PROGRESS);
        Integer deliveryInProgress = (int) count(queryWrapper);
        queryWrapper.clear();
        //待接单
        queryWrapper.eq(Orders::getStatus,Orders.TO_BE_CONFIRMED);
        Integer toBeConfirmed = (int) count(queryWrapper);
        return OrderStatisticsVO.builder()
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .toBeConfirmed(toBeConfirmed)
                .build();
    }

    //商家完成订单
    @Override
    public void complete(Long id) {
        //判断订单是否存在
        Orders orders = checkOrdersExist(id);
        //如果订单状态不=4抛出异常
        if(!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //更新订单信息
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                .eq(Orders::getId, id)
                .set(Orders::getStatus, Orders.COMPLETED)
                .set(Orders::getDeliveryTime,LocalDateTime.now());
        update(updateWrapper);
    }

    //商家拒单
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //判断订单是否存在
        Orders orders = checkOrdersExist(ordersRejectionDTO.getId());
        //如果订单状态不=2抛出异常
        if(!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //如果客户已支付需退款
        if(orders.getPayStatus().equals(Orders.PAID)) refund(orders.getNumber(),orders.getAmount());
        //更新订单信息
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                .eq(Orders::getId, ordersRejectionDTO.getId())
                .set(Orders::getStatus, Orders.CANCELLED)
                .set(Orders::getRejectionReason, ordersRejectionDTO.getRejectionReason());
        update(updateWrapper);
    }

    //商家接单
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //判断订单是否存在
        checkOrdersExist(ordersConfirmDTO.getId());
        //更新订单信息
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                .eq(Orders::getId, ordersConfirmDTO.getId())
                .set(Orders::getStatus, Orders.CONFIRMED);
        update(updateWrapper);
    }

    //商家派单
    @Override
    public void delivery(Long id) {
        //判断订单是否存在
        Orders orders = checkOrdersExist(id);
        //如果订单状态不=3抛出异常
        if(!orders.getStatus().equals(Orders.CONFIRMED)) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //更新订单信息
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                .eq(Orders::getId, id).
                set(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS);
        update(updateWrapper);
    }

    //商家分页查询订单
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        Page<Orders> page = Page.of(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> result = lambdaQuery()
                .gt(ordersPageQueryDTO.getBeginTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getBeginTime())
                .le(ordersPageQueryDTO.getEndTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getEndTime())
                .like(ordersPageQueryDTO.getNumber() != null, Orders::getNumber, ordersPageQueryDTO.getNumber())
                .like(ordersPageQueryDTO.getPhone() != null, Orders::getPhone, ordersPageQueryDTO.getPhone())
                .eq(ordersPageQueryDTO.getStatus() != null, Orders::getStatus, ordersPageQueryDTO.getStatus())
                .page(page);
        List<OrderVO> orderVOS = BeanUtil.copyToList(result.getRecords(), OrderVO.class);
        for (OrderVO orderVO : orderVOS) {
            //菜品详情
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<OrderDetail>()
                    .eq(OrderDetail::getOrderId, orderVO.getId());
            List<String> collect = orderDetailMapper.selectList(queryWrapper).stream().map(o -> o.getName() + "*" + o.getNumber()).collect(Collectors.toList());
            String join = String.join("+", collect);
            orderVO.setOrderDishes(join);
            //地址详情
            String addressBookString = getAddressBookString(orderVO.getAddressBookId());
            orderVO.setAddress(addressBookString);
        }
        return new PageResult(result.getTotal(),orderVOS);
    }

    //客户取消订单
    @Override
    public void userCancel(Long id) throws Exception {
        //判断订单是否存在
        Orders orders = checkOrdersExist(id);
        //如果订单状态不为 待付款 or 待接单
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //退款
            refund(orders.getNumber(),orders.getAmount());
            //更新订单信息
            LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                    .eq(Orders::getId, orders.getId())
                    .set(Orders::getPayStatus, Orders.REFUND)
                    .set(Orders::getStatus, Orders.CANCELLED)
                    .set(Orders::getCancelReason, "客户取消")
                    .set(Orders::getCancelTime, LocalDateTime.now());
            update(updateWrapper);
        }
    }

    //客户催单
    @Override
    public void reminder(Long id) {
        //判断订单是否存在
        Orders orders = checkOrdersExist(id);
        //提醒商家
        NotifyVO notifyVO = new NotifyVO(2, id, "订单号:"+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(notifyVO));
    }

    //统计日营业额
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //生成日营业额数据字符串
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.COMPLETED)
                .between(Orders::getOrderTime, beginTime, endTime);
        List<Orders> list = list(queryWrapper);
        Map<LocalDate, BigDecimal> collect = list
                .stream()
                .collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate(),
                        Collectors.mapping(Orders::getAmount, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
        for (LocalDate date = begin; date.isBefore(end.plusDays(1)); date = date.plusDays(1)) {
            collect.putIfAbsent(date, BigDecimal.ZERO);
        }
        ArrayList<BigDecimal> amountList = new ArrayList<>(collect.values());
        String amountListString = StringUtils.join(amountList, ",");
        //日期字符串
        String dateListString = getDateListString(begin, end);
        return new TurnoverReportVO(dateListString,amountListString);
    }

    //统计订单
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //查询时间段内的订单
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .between(Orders::getOrderTime, beginTime, endTime);
        List<Orders> ordersList = list(queryWrapper);
        //统计每日订单数
        Map<LocalDate, Long> totalEveryday = ordersList.stream()
                .collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate(), Collectors.counting()));
        for (LocalDate date = begin; date.isBefore(end.plusDays(1)); date = date.plusDays(1)) {
            totalEveryday.putIfAbsent(date, 0L);
        }
        ArrayList<Long> totalEverydayList = new ArrayList<>(totalEveryday.values());
        Collections.reverse(totalEverydayList);
        String totalEverydayListString = StringUtils.join(totalEverydayList, ",");
        //统计每日有效订单数
        Map<LocalDate, Long> validEveryday = ordersList.stream()
                .filter(o -> o.getStatus().equals(Orders.COMPLETED))
                .collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate(), Collectors.counting()));
        for (LocalDate date = begin; date.isBefore(end.plusDays(1)); date = date.plusDays(1)) {
            validEveryday.putIfAbsent(date, 0L);
        }
        ArrayList<Long> validEverydayList = new ArrayList<>(validEveryday.values());
        Collections.reverse(validEverydayList);
        String validEverydayListString = StringUtils.join(validEverydayList, ",");
        //统计总订单数
        long total = totalEverydayList.stream().reduce(Long::sum).get();
        //统计总有效订单数
        long valid = validEverydayList.stream().reduce(Long::sum).get();
        //统计订单完成率
        Double completionRate = total==0?0.00:BigDecimal.valueOf(valid).divide(BigDecimal.valueOf(total), 4, RoundingMode.HALF_UP).doubleValue();
        //日期字符串
        String dateListString = getDateListString(begin, end);
        return new OrderReportVO(dateListString,totalEverydayListString,validEverydayListString,total,valid,completionRate);
    }

    //统计菜品销量top10
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //查询已完成的订单
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus, Orders.COMPLETED)
                .between(Orders::getOrderTime, beginTime, endTime)
                .select(Orders::getId);
        List<Long> ids = list(queryWrapper).stream().map(Orders::getId).collect(Collectors.toList());
        //查询订单详情
        LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<OrderDetail>()
                .in(OrderDetail::getOrderId, ids);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper1);
        //对集合按名称分组并统计数量
        Map<String, Integer> collect = orderDetails.stream()
                .collect(Collectors.groupingBy(OrderDetail::getName, Collectors.summingInt(OrderDetail::getNumber)));
        //对集合按降序排序取前10个
        LinkedHashMap<String, Integer> sortCollect = collect.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .limit(10)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new));
        //top10名称数组
        ArrayList<String> nameList = new ArrayList<>(sortCollect.keySet());
        String nameListString = StringUtils.join(nameList, ",");
        //top10数量数组
        ArrayList<Integer> numberList = new ArrayList<>(sortCollect.values());
        String numberListString = StringUtils.join(numberList, ",");
        return new SalesTop10ReportVO(nameListString,numberListString);
    }

    //生成日期数组字符串
    private static String getDateListString(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        return StringUtils.join(dateList, ",");
    }

    //获取客户地址并转为字符串
    public String getAddressBookString(Long addressBookId){
        LambdaQueryWrapper<AddressBook> queryWrapper2 = new LambdaQueryWrapper<AddressBook>()
                .eq(AddressBook::getId, addressBookId);
        AddressBook addressBook = addressBookMapper.selectOne(queryWrapper2);
        StringJoiner stringJoiner = new StringJoiner("-");
        return stringJoiner
                .add(addressBook.getProvinceName())
                .add(addressBook.getCityName())
                .add(addressBook.getDistrictName())
                .add(addressBook.getDetail())
                .toString();
    }

    //判断订单是否存在
    private Orders checkOrdersExist(Long id) {
        Orders orders = getById(id);
        if(orders==null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        else return orders;
    }

    //退款
    public void refund(String orderNumber,BigDecimal amount) throws Exception {
        String refund = weChatPayUtil.refund(
                orderNumber, //商户订单号
                orderNumber, //商户退款单号
                amount, //退款金额，单位:元
                amount); //原订单金额
    }

    //调用百度地图接口判断客户地址是否超出配送范围
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);
        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        log.info("店铺经纬度坐标: {}",shopCoordinate);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }
        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;
        map.put("address", address);
        //获取客户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        log.info("客户地址经纬度坐标: {}",userCoordinate);
        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }
        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //客户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;
        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");
        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }
        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        log.info("距离: {}",distance);
        //如果超出配送范围
        if (distance > 10000) throw new OrderBusinessException("超出配送范围");
    }

}